<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Setu Gallery</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.5.0/sql-wasm.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        h1 {
            font-size: 50px;
            margin-top: 20px;
        }
        input, button, label {
            margin: 10px;
        }
        #keyword {
            min-width: 500px;
        }
        #results {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            padding: 20px;
            box-sizing: border-box;
            max-width: 100%;
        }
        #filter-options {
            display: flex;
            gap: 10px;
        }
        .result-item {
            flex: 1 1 calc(33.333% - 20px);
            box-sizing: border-box;
            margin: 10px;
            text-align: center;
        }
        .result-item img {
            max-height: 50vh; /* Height of the image as half of the device height */
            width: auto;
            max-width: 100%;
            height: auto;
        }
        .query-info, .pagination {
            margin: 10px;
        }
    </style>
</head>
<body>
    <h1 id="page-title">LoliconDB Gallery</h1>
    <input type="file" id="dbfile" accept=".db" />
    <input type="text" id="keyword" placeholder="Enter keywords separated by ','(多个tag用英文逗号分割)">
    <div id="filter-options">
        <label>
            <input type="checkbox" id="onlyGenshin">
            Only Genshin
        </label>
        <label>
            <input type="checkbox" id="showR18">
            Show R18
        </label>
    </div>
    <button onclick="fetchData()">Search</button>
    <div class="query-info" id="queryInfo"></div>
    <div id="results"></div>
    <div class="pagination" id="paginationControls"></div>

    <script>
        let db;
        let currentPage = 1;
        const resultsPerPage = 100;
        let totalResults = 0;

        document.getElementById('dbfile').addEventListener('change', (event) => {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = function() {
                const Uints = new Uint8Array(reader.result);
                initSqlJs({locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.5.0/sql-wasm.wasm`}).then(SQL => {
                    db = new SQL.Database(Uints);
                    console.log('Database loaded');
                }).catch(error => {
                    console.error('Error loading SQL.js:', error);
                });
            };
            reader.readAsArrayBuffer(file);
        });

        async function fetchData(page = 1) {
            currentPage = page;

            if (!db) {
                alert('Please upload file "lolicon.db" first');
                return;
            }

            const keywords = document.getElementById('keyword').value.split(',').map(kw => kw.trim());
            if (keywords.length === 0 || keywords[0] === '') {
                alert('Please enter at least one keyword');
                return;
            }

            const onlyGenshin = document.getElementById('onlyGenshin').checked;
            const showR18 = document.getElementById('showR18').checked;
            const conditions = keywords.map(kw => `(tags LIKE '%${kw}%' OR title LIKE '%${kw}%')`).join(' AND ');

            // First, query total count
            let countQuery = `SELECT COUNT(*) as count FROM main WHERE (${conditions})`;
            if (onlyGenshin) {
                countQuery += ` AND (tags LIKE '%原神%' OR tags LIKE '%Genshin%')`;
            }
            if (!showR18) {
                countQuery += ` AND r18 != 1`;
            }
            const countResults = db.exec(countQuery);
            totalResults = countResults.length > 0 ? countResults[0].values[0][0] : 0;

            // Query for current page
            let query = `SELECT pid, title, author, r18, tags, urls FROM main WHERE (${conditions})`;
            if (onlyGenshin) {
                query += ` AND (tags LIKE '%原神%' OR tags LIKE '%Genshin%')`;
            }
            if (!showR18) {
                query += ` AND r18 != 1`;
            }
            query += ` ORDER BY pid DESC LIMIT ${resultsPerPage} OFFSET ${(page - 1) * resultsPerPage}`;

            try {
                const results = db.exec(query);
                const resultsDiv = document.getElementById('results');
                resultsDiv.innerHTML = '';

                const queryInfoDiv = document.getElementById('queryInfo');
                const r18Results = results.length > 0 ? results[0].values.filter(row => row[3] == 1).length : 0;

                queryInfoDiv.innerHTML = `Total results: ${totalResults}, R18 results: ${r18Results}`;

                if (totalResults === 0) {
                    resultsDiv.innerHTML = 'No results found.';
                    updatePaginationControls(0);
                    return;
                }

                results[0].values.forEach(row => {
                    const div = document.createElement('div');
                    div.classList.add('result-item');
                    div.innerHTML = `
                        <p>Title: ${row[1]}</p>
                        <p>Author: ${row[2]}</p>
                        <p>PID: ${row[0]}</p>
                        <p>Tags: ${row[4]}</p>
                        <img src="${row[5].replace('i.pixiv.cat', 'i.pixiv.re')}" alt="Setu Image">
                    `;
                    resultsDiv.appendChild(div);
                });

                updatePaginationControls(totalResults);
            } catch (error) {
                console.error('Query execution error:', error);
            }
        }

        function updatePaginationControls(totalResults) {
            const paginationControls = document.getElementById('paginationControls');
            paginationControls.innerHTML = '';

            const totalPages = Math.ceil(totalResults / resultsPerPage);
            const prevButton = document.createElement('button');
            prevButton.innerText = 'Previous';
            prevButton.disabled = currentPage <= 1;
            prevButton.onclick = () => fetchData(currentPage - 1);
            paginationControls.appendChild(prevButton);

            const nextButton = document.createElement('button');
            nextButton.innerText = 'Next';
            nextButton.disabled = currentPage >= totalPages;
            nextButton.onclick = () => fetchData(currentPage + 1);
            paginationControls.appendChild(nextButton);
        }
    </script>
</body>
</html>
